<?PHP
  session_start();
		include('geo.php');
 
  function delete_listing()
  {

        $url = $_GET['url'];

        $sql = "SELECT * FROM listings WHERE url = '" . $url . "'";

        //echo $sql;


        if(!($test = mysql_query($sql)))
          badreq(mysql_error()." ".$sql);



        if($row = mysql_fetch_array($test))

        {

           $del = "DELETE FROM listings WHERE url = '" . $url . "'";


           if(!(mysql_query($del)))
             badreq(mysql_error()." ".$del);


           //$rsp = 'rsp = {"function":"delete_listing"}'; 
		   fnc_table();
        }

        else

        {

         badreq("This listing does not exist");

        }

  }
   
  function settings_remove()
  {
     $region = $_GET['region'];
        $id = $_SESSION['userid'];
        $regarr = explode(",", $region);
        if(sizeof($regarr)==2)
        {
         $place  = $regarr[0];
         $state  = trim($regarr[1]);
        }
        $sql1 = "SELECT id FROM locations WHERE name = '" . $place . "' AND state = '" . $state . "'";

       if(!($loc = mysql_query($sql1)))
         badreq(mysql_error()." ".$sql1);



       if($row1 = mysql_fetch_array($loc))//loc id
       {
          $sql2 = "SELECT location_id FROM user_locations WHERE user_id = " . $id;
          $bool2=false;
          if (($test2 = mysql_query($sql2)) == null)
            output(mysql_error()."<p>$sql2</p>");
          while($row2 = mysql_fetch_array($test2)) //yes, its a fav

          {
            if($row2['location_id'] == $row1['id'])
            {
              $bool2 = true;
            }
          }
          if(!$bool2)
          {
           badreq("This location is not a favorite");
          }
          else //ok to delete
          {
            $del = "DELETE FROM user_locations WHERE location_id = " . $row1['id'] . " AND user_id = " . $id;
            //echo $del;

            if(!(mysql_query($del)))
              badreq(mysql_error()." ".$del);


            //$rsp = 'rsp = {"function":"settings_remove"}';
				        user_settings();
  }
  }
  }


function user_settings(){
	$id = $_SESSION['userid'];
    //echo $id;
    //get location id's to userid, for each id, get stats data
    $qry  = "SELECT l.name, l.state ";
    $qry .= "FROM user_locations ul, locations l ";
    $qry .= "WHERE ul.user_id = $id ";
    $qry .= "AND   l.id = ul.location_id";
    //echo $qry;
    if (($locs = mysql_query($qry)) == null)
      output(mysql_error()."<p>$qry</p>");
    $arr = array();
    
    //rss link
    $sql = "SELECT rss_url FROM users WHERE id = " . $id;
    if (($rss_url = mysql_query($sql)) == null)
      output(mysql_error()."<p>$sql</p>");
    $json = "rsp = {\"function\":\"user_settings\",\"array\":[";
	 while($row = mysql_fetch_array($locs))
    {
      $nm = ucwords($row['name']);
      $nm = trim($nm, " ");
      $st = strtoupper($row['state']);
      $json .= "\"$nm, $st\",";
    }
	$json .= "],\"rss\":\"";
    if($row2 = mysql_fetch_array($rss_url))
    {
      $json .= $row2['rss_url'];
	  $json .= '"};';
    }
    output($json); 
}
		 
  function home()
  {
    $id = $_SESSION['userid'];
    //echo $id;
    //get location id's to userid, for each id, get stats data
    $qry  = "SELECT l.name, l.state ";
    $qry .= "FROM user_locations ul, locations l ";
    $qry .= "WHERE ul.user_id = $id ";
    $qry .= "AND   l.id = ul.location_id";
    //echo $qry;
    if (($locs = mysql_query($qry)) == null)
      output(mysql_error()."<p>$qry</p>");
    $arr = array();
    while($row = mysql_fetch_array($locs))
    {
      //$nm = $row['name'];
      $st = $row['state'];
      $nm = ucwords($row['name']);
      $nm = trim($nm, " ");
      $st = strtoupper($row['state']);
      $arr[] = "$nm, $st";
    }
    //rss link
    $sql = "SELECT rss_url FROM users WHERE id = " . $id;
    if (($rss_url = mysql_query($sql)) == null)
      output(mysql_error()."<p>$sql</p>");
    $json = "rsp = {\"function\":\"home\",\"rss\":\"";
    if($row2 = mysql_fetch_array($rss_url))
    {
      $json .= $row2['rss_url'] . '"';
    }
    //$json .= "\",\"chart\":";
    $chart = home_chart_multi($arr);
    //$chart = "link to chart_multi";
    $json .= $chart;
    output($json);
  } 
    
  function settings_add()
  {
    $region = $_GET['region'];
    $id     = $_SESSION['userid'];
    $regarr = explode(",", $region);

				//echo "<p>userid: ".$_SESSION['userid']."</p>";

    if(sizeof($regarr)==2)
    {
     $place  = $regarr[0];
     $state  = trim($regarr[1]);
    }
    $sql1 = "SELECT COUNT(location_id) FROM user_locations WHERE user_id = " . $id;
    if (!($test1 = mysql_query($sql1)))
						badreq(mysql_error()."<p>$sql1</p>");
    if($row = mysql_fetch_array($test1))
    {
     $c = $row[0];
     if($c < 5) //locs less than 5
     {
      $ins1 = "SELECT id FROM locations WHERE name = '" . $place . "' AND state = '" . $state . "'";
           if (!($loc = mysql_query($ins1)))
						       badreq(mysql_error()."<p>$ins1</p>");
           if($row1 = mysql_fetch_array($loc))//loc id
           {
              $sql2 = "SELECT location_id FROM user_locations WHERE user_id = " . $id;
              $bool2=false;
              if (!($test2 = mysql_query($sql2)))
						          badreq(mysql_error()."<p>$sql2</p>");

              while($row2 = mysql_fetch_array($test2)) //already a fav
              {
                if($row2['location_id'] == $row1['id'])
                {
                  $bool2 = true;
                }
              }
              if($bool2)
              {
               badreq("This location is already a favorite");
              }
              else //ok to insert
              {
                $ins = "INSERT INTO user_locations (location_id, user_id) VALUES(" . $row1['id'] . ", " . $id . ")";
                //echo $ins;
                if(!(mysql_query($ins)))
						            badreq(mysql_error()."<p>$ins</p>");
                //$rsp = 'rsp = {"function":"settings_add"}';
                //output($rsp);
              }
           }
											else
											  badreq("location not on craigslist");
        }
      }
      else
      {
          badreq("This user already has 5 favorite regions");
      }

				user_settings();
  }
   
  function chart_base()
  {
    $arr[] = "albany, ny";
    output(chart_multi($arr));
  }
  
  function getChartArr()
  {
				$reg = $_GET['region'];
				$arr = explode(";", $reg);
    return $arr;
  }
   
  function delUser()
  {
    $username = $_GET['username'];
    $qry  = "SELECT id FROM users WHERE username='$username' AND is_admin=0";

    if(!($test = mysql_query($qry)))
      badreq(mysql_error()." ".$qry);


    if($row = mysql_fetch_array($test))
    {
      //delete
      $sql = "DELETE FROM users WHERE username = '" . $username . "'";

      if(!(mysql_query($sql)))
        badreq(mysql_error()." ".$sql);


        $rsp = 'rsp = {"function":"delete_user"}';
        output($rsp);
    }
    else
    {
      badreq("could not delete user");
    }
  }
   
  function genUrl($user)
  {
    return "feed.php?username=$user&rand=".rand(0,100000000000);
  }
   
  function loseLastChar($str)
  {
    $len = strlen($str);
			 $str =	substr($str, 0, $len - 1);
				return $str;
  }
    
		function getListings($place, $state)
		{
				/* 
				   return only listings
				*/
				 
				mysql_connect("localhost", "websys", "websys");
				mysql_select_db("final_proj");
				 
				$sql  = "SELECT li.title AS title, li.url AS url, li.price AS price ";
				$sql .= "FROM locations lo, listings li ";
				$sql .= "WHERE lo.state LIKE '%$state%' ";
				$sql .= "AND   lo.name  LIKE '%$place%' ";
				$sql .= "AND   lo.id   = li.location_id ";
				 
				//print_r($sql);
				if (($res = mysql_query($sql)) == null) badreq(mysql_error()."query: ".$sql);
     
				$listings = array();
				while (($row = mysql_fetch_array($res)) != null)
				{
       $listings[] = array("title" => $row['title'], 
							                    "link"  => $row['url'], 
							                    "price" => $row['price']);
				}
				mysql_close();
				
				$rsp = 'rsp =';
				$rsp .= '{';
				$rsp .= '"function":"table",';
    $rsp .= '"error":"",';
				$rsp .= '"level":"Location",';
				$rsp .= '"listing":"'.$place.', '.$state.'",';
				$rsp .= '"headers":[';
				$rsp .= '"Title",';
				$rsp .= '"Price",';
				$rsp .= '"Link"';
    $rsp .= '],';
    $rsp .= '"array":[';
				foreach ($listings as $listing)
				{
						$title = $listing['title'];
						$price = $listing['price'];
						$link  = $listing['link'];
						 
				  $rsp  .= '["'.$title.'",';
				  $rsp  .=  '"'.$price.'",';
				  $rsp  .=  '"<a href=\"'.$link .'\">link</a>"],';
				}
    $rsp  = loseLastChar($rsp);
				$rsp .= ']};';

				output($rsp);
		}
		 
		function getStatsByState($state)
		{
				/*
       return list of locations within 
							state with stats for each
				*/
				$rsp = 'rsp=';
				
				mysql_connect("localhost", "websys", "websys");
				mysql_select_db("final_proj");
				 
				$sql  = "SELECT * ";
				$sql .= "FROM  locations l, stats s ";
				$sql .= "WHERE l.state       = '$state' ";
				$sql .= "AND   s.location_id = l.id ";
				  
				//echo $sql;
				if (($res = mysql_query($sql)) == null) badreq(mysql_error()."query: ".$sql);
     
				$stats = array();
				while (($row = mysql_fetch_array($res)) != null)
				{
       $stats[] = array("name"           => $row['name'], 
							                 "dtime"          => $row['dtime'],
							                 "avg_age"        => $row['avg_age'],
							                 "population"     => $row['population'],
							                 "total_listings" => $row['total_listings'],
							                 "avg_price"      => $row['avg_price']);
				}
				 
				mysql_close();
				
				$rsp = 'rsp=';				
				$rsp .= '{';
				$rsp .= '"function":"table",';
    			$rsp .= '"error":"",';
				$rsp .= '"level":"State",';
				$rsp .= '"listing":"'.$state.'",';
				$rsp .= '"headers":[';
				$rsp .= '"Place",';
				$rsp .= '"Average Age",';
				$rsp .= '"# of Listings",';
				$rsp .= '"Average Price"';
    $rsp .= '],';
    $rsp .= '"array":[';
    //print_r($stats);
				foreach ($stats as $location)
				{
						$place          = $location['name'];
						$avg_price      = $location['avg_price'];
						$total_listings = $location['total_listings']; 
						$population     = $location['population']; 
						$avg_age        = $location['avg_age']; 
						 
				  $rsp  .= '["'.$place         .'",';
				  $rsp  .=  '"'.$avg_age       .'",';
				  $rsp  .=  '"'.$population    .'",';
				  $rsp  .=  '"'.$total_listings.'",';
				  $rsp  .=  '"'.$avg_price     .'"],';
				}
    $rsp  = loseLastChar($rsp);
				$rsp .= ']}';
     
				output($rsp);
		}
		 
		function getStatsByNation()
		{
				/*
       return list of states 
							with stats for each
				*/
				 
				mysql_connect("localhost", "websys", "websys");
				mysql_select_db("final_proj");
				 
				$sql  = "SELECT l.state AS state, ";
				$sql .= "       SUM(s.total_listings) AS total_listings, ";
				$sql .= "							AVG(s.avg_price) AS avg_price ";
				$sql .= "FROM  locations l, stats s ";
				$sql .= "WHERE l.state       = `$state` ";
				$sql .= "AND   s.location_id = l.id ";
				$sql .= "GROUP BY l.state ";
				  
				if (($res = mysql_query($sql)) == null) badreq(mysql_error()."query: ".$sql);
     
    $states = array();
				while (($row = mysql_fetch_array($res)) != null)
				{
       $states[] = array($row['state'], 
							                  $row['total_listings'],
							                  $row['avg_price']);
				}
				 
				mysql_close();
				  
				$rsp .= '{';
				$rsp .= '"function":"table",';
    $rsp .= '"error":"",';
				$rsp .= '"level":"Nation",';
				$rsp .= '"listing":"States",';
				$rsp .= '"headers":[';
				$rsp .= '"State",';
				$rsp .= '"# of Listings",';
				$rsp .= '"Average Price"';
    $rsp .= '],';
    $rsp .= '"array":[';
				foreach ($states as $location)
				{
						$state          = $location['state'];
						$total_listings = $location['total_listings'];
						$avg_price      = $location['avg_price'];
						 
				  $rsp  .= '["'.$state         .'",';
				  $rsp  .=  '"'.$total_listings.'",';
				  $rsp  .=  '"'.$avg_price     .'"],';
				}
    $rsp  = loseLastChar($rsp);
				$rsp .= ']};';

				output($rsp);
		}
   
		function parseRegion($region)
		{
				if (empty($region))
				  $region = $_GET['region'];
				if (empty($region)) 
						badreq("bad region");
     			
				if ($region == "National" || $region == "national")
					return array("place" => $region, "state" => $region);
					
				$region = urldecode($region);
				$region = strtolower($region);
       
				$regarr = explode(",", $region);
				$place  = trim($regarr[0], " \t");
				$state  = trim($regarr[1], " \t"); 
     
				if (empty($state) && !empty($place))
				{
						$state = $place;
						$place = "";
				}
				return array("place" => $place, "state" => $state);
		}
		 
		function fnc_table()
		{
				/*
			rsp={
			"function":"table",
			"level":"Nation",
			"listing":"State",
			"headers":[
			  "State Name",
			  "Avg. Price",
			  "Avg. Age",
			  "# of Listings"
			],
			"array":[
			  ["New York", "-69", "-69", "-69"],
			  ["askdfkal", "-69", "-69", "-69"]
			]
			};
				*/
			$region = $_GET['region'];	 
			//$rsp = 'rsp =';
			$ps = parseRegion($region);
				 
			// this should go before the sql only
			$place = mysql_real_escape_string($ps['place']);
			$state = mysql_real_escape_string($ps['state']);
			
			/* 
			still need to distinguish between place 
			and state in absence of comma
			*/
				if (!empty($place) && !empty($state))
						getListings($place, $state);
				elseif ($place == "National" || $place == "national")
						getStatsByNation();
				elseif ($state)
						getStatsByState($state);
				else
						getStatsByNation();
		}
   
		function badreq($err = "that\'s what she said")
		{
			$err  = json_encode($err);
			$rsp  = 'rsp=';
			$rsp .= '{';
			$rsp .= '"function":"error",';
			$rsp .= '"error":'.$err;
			$rsp .= '};';

				output($rsp);
		}
   
function checkSession($id)
{
	$ssid = session_id();
	//$ssid = 123;
	if($ssid == $id) 
		return 1;
	else 
		return 0;
}
   
function get_age_gender() 
{
	$region = $_GET['region'];
	$ps     = parseRegion($region);
	$zip    = getZip($ps['place'], $ps['state']);
	$url    = "http://pics4.city-data.com/zag/za$zip.png";
	output($url);
}
		 
function auth_user()
{
    $username = $_POST['username'];
    $password = $_POST['password'];
				//echo "$username    $password";
    $err  = "";
    $ssid = session_id();
    $qry1 = "SELECT id FROM users WHERE username = '" . $username . "'";
    //echo $qry1;
    if(($test1 = mysql_query($qry1)) == null)
						output(mysql_error()."<p>$qry1</p>");
    if($row1 = mysql_fetch_array($test1) )
    {
      $qry2 = "SELECT * FROM users WHERE username = '" . $username . "'
             AND password = '" . $password . "'";
      // echo $qry2;

      if(!($test2 = mysql_query($qry2)))
        badreq(mysql_error()." ".$qry2);


      if($row2 = mysql_fetch_array($test2))
      {
        //JSON true, $username, $password
        $succ = "true";
								$_SESSION['userid'] = $row2['id'];
								$is_admin = $row2['is_admin'];
      }
      else
      {
         //JSON  false, $user, $pass
         $succ = "false";
         $err  = "Incorrect Password";
								 $is_admin = 0;
      }
    }
    else
    {
      //JSON false, user doesnt exist
      $succ = "false";
      $err  = "User Does Not Exist";
						$is_admin = 0;
    }
    $json  = "{\"success\":\"$succ\",";
    $json .=  "\"user\":\"$username\",";
    $json .=  "\"ssid\":\"$ssid\",";
    $json .=  "\"is_admin\":\"$is_admin\",";
    $json .=  "\"error\":\"$err\"}";
    echo $json;
  }
    
  function addUser()
  {
    $username = $_GET['username'];
    $password = $_GET['password'];
	$password = trim($password);
    $qry = "SELECT id FROM users WHERE username = '" . $username . "'";
    //echo $qry1;

    if(!($test = mysql_query($qry)))
      badreq(mysql_error()." ".$qry);


    if($row = mysql_fetch_array($test) )
    {
      badreq("user exists");
    }
    else
    {
      $url  = genUrl($username);
      $sql  = "INSERT INTO users(username, password, rss_url, is_admin) ";
      $sql .= "VALUES('$username','$password','$url','0')";
      if(mysql_query($sql))
      {
        $rsp = 'rsp = {"function":"add_user"}';
        output($rsp);
      }
      else
        badreq("failed to add user: ".mysql_error()."<p>$sql</p>");
    }
  }
  
  function home_chart_multi($arr)
  {
				if (empty($arr) || $arr[0] == "national")
						$arr[] = "reno, nv";
				mysql_connect("localhost", "websys", "websys");
				mysql_select_db("final_proj");
    $str = ",\"chart_src\":[";
    $str0 ="\"http://chart.apis.google.com/chart?chs=600x400&amp;chco=00FF00&amp;chts=000000,20&amp;chf=bg,s,EFEFEF&amp;chbh=a&amp;cht=bvg&amp;";
    $str1="chtt=Average+Price+(Dollars)&amp;chd=t:";
    $str2="chtt=Average+Gender+Ratio+(Females+to+Males)&amp;chd=t:";
    $str3="chtt=Average+Income+(Dollars)&amp;chd=t:";
    $str4="chtt=Average+Age+(Years)&amp;chd=t:";
    $str5="chtt=Average+Population+(People)&amp;chd=t:";
    $str6="chtt=Average+Total+Listings+(Listings)&amp;chd=t:";

    $max_avg_p=0;
    $max_avg_gr = 0;
    $max_avg_inc = 0;
    $max_avg_age = 0;
    $max_pop = 0;
    $max_tot_list = 0;
    
    $labels = array();

    foreach($arr as $item)
    {
      //echo $item . "<br/>";
						$item = strtolower($item);
      $regarr = explode(",", $item);

      if(sizeof($regarr)==2)
      {
       $place  = $regarr[0];
       $state  = trim($regarr[1]);
       $labels[] = $place . ", " . $state;

      }
      else
      {
        $place="";
        $state = $regarr[0];
        $labels[] = $state;
      }
      //only state
      if($place=="")
      {
        $sql = "SELECT DISTINCT avg(avg_price) AS AvgPrice, avg(gender_ratio) AS AvgGenderRatio,
                       avg(avg_income) AS AvgIncome, avg(avg_age) AS AvgAge,
                       avg(population) AS AvgPopulation, avg(total_listings) AS AvgTotalListings
                  FROM stats
                  JOIN locations ON stats.location_id = locations.id
                  WHERE locations.state = '" . $state . "'
                  GROUP BY locations.state";
        if (($data = mysql_query($sql)) == null)
          output(mysql_error()."<p>$sql</p>");
        $stats="<b>" . $state . "</b>";
        //echo $sql;

        if($row = mysql_fetch_array($data))
        {
            $avg_p = $row['AvgPrice'];
            $avg_gr = $row['AvgGenderRatio'];
            $avg_inc = $row['AvgIncome'];
            $avg_age = $row['AvgAge'];
            $pop = $row['AvgPopulation'];
            $tot_list = $row['AvgTotalListings'];
           
            if($avg_p > $max_avg_p) $max_avg_p = $avg_p;
            if($avg_gr > $max_avg_gr) $max_avg_gr = $avg_gr;
            if($avg_inc > $max_avg_inc) $max_avg_inc = $avg_inc;
            if($avg_age > $max_avg_age) $max_avg_age = $avg_age;
            if($pop > $max_pop) $max_pop = $pop;
            if($tot_list > $max_tot_list) $max_tot_list = $tot_list;
           
            $str1 .= $avg_p . ",";
            $str2 .= $avg_gr . ",";
            $str3 .= $avg_inc . ",";
            $str4 .= $avg_age . ",";
            $str5 .= $pop . ",";
            $str6 .= $tot_list . ",";
        }
      }
      else //city and state
      {
        //get city id
        $sql = "SELECT id FROM locations WHERE name = '" . $place . "' AND state = '" . $state . "'";
        //echo $sql;

        if(!($loc = mysql_query($sql)))
          badreq(mysql_error()." ".$sql);


        if($row = mysql_fetch_array($loc))
        {
          $city_id = $row['id'];
          $sql2 = "SELECT * FROM stats where location_id = " . $city_id . " LIMIT 1";

          if(!($data = mysql_query($sql2)))
            badreq(mysql_error()." ".$sql2);


          $stats = "<b>" . $place . ", " . $state . "</b><br/>";
          while($row2 = mysql_fetch_array($data))
          {
            $avg_p = $row2['avg_price'];
            $avg_gr = $row2['gender_ratio'];
            $avg_inc = $row2['avg_income'];
            $avg_age = $row2['avg_age'];
            $pop = $row2['population'];
            $tot_list = $row2['total_listings'];

            if($avg_p > $max_avg_p) $max_avg_p = $avg_p;
            if($avg_gr > $max_avg_gr) $max_avg_gr = $avg_gr;
            if($avg_inc > $max_avg_inc) $max_avg_inc = $avg_inc;
            if($avg_age > $max_avg_age) $max_avg_age = $avg_age;
            if($pop > $max_pop) $max_pop = $pop;
            if($tot_list > $max_tot_list) $max_tot_list = $tot_list;

            $str1 .= $avg_p . ",";
            $str2 .= $avg_gr . ",";
            $str3 .= $avg_inc . ",";
            $str4 .= $avg_age . ",";
            $str5 .= $pop . ",";
            $str6 .= $tot_list . ",";

          }
        }
      }

    }
    $max = "Max Data<br/>";
    $max .= "avg_p: " . number_format($max_avg_p, 2) . "<br/>";
    $max .= "avg_gr: " . number_format($max_avg_gr, 2) . "<br/>";
    $max .= "avg_inc: " . number_format($max_avg_inc, 2) . "<br/>";
    $max .= "avg_age: " . number_format($max_avg_age, 0) . "<br/>";
    $max .= "max_pop: " . number_format($max_pop, 0) . "<br/>";
    $max .= "max_tot_list :" . number_format($max_tot_list, 0) . "<br/>";
    
    $str1 = substr_replace($str1, "", -1);
    $str1 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_p . "," . $max_avg_p/10 . "&amp;chds=0," . $max_avg_p . "&amp;chl=";

    $str2 = substr_replace($str2, "", -1);
    $str2 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_gr . "," . $max_avg_gr/10 . "&amp;chds=0," . $max_avg_gr . "&amp;chl=";

    $str3 = substr_replace($str3, "", -1);
    $str3 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_inc . "," . $max_avg_inc/10 . "&amp;chds=0," . $max_avg_inc . "&amp;chl=";

    $str4 = substr_replace($str4, "", -1);
    $str4 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_age . "," . $max_avg_age/10 . "&amp;chds=0," . $max_avg_age . "&amp;chl=";

    $str5 = substr_replace($str5, "", -1);
    $str5 .= "&amp;chxt=y&amp;chxr=0,0," . $max_pop . "," . $max_pop/10 . "&amp;chds=0," . $max_pop . "&amp;chl=";

    $str6 = substr_replace($str6, "", -1);
    $str6 .= "&amp;chxt=y&amp;chxr=0,0," . $max_tot_list . "," . $max_tot_list/10 . "&amp;chds=0," . $max_tot_list . "&amp;chl=";

    
    foreach($labels as $label)
    {
      $str1 .= $label . "|";
      $str2 .= $label . "|";
      $str3 .= $label . "|";
      $str4 .= $label . "|";
      $str5 .= $label . "|";
      $str6 .= $label . "|";

    }
    $str1 = substr_replace($str1, "", -1);
    $str1 .= "\"";

    $str2 = substr_replace($str2, "", -1);
    $str2 .= "\"";
    
    $str3 = substr_replace($str3, "", -1);
    $str3 .= "\"";
    
    $str4 = substr_replace($str4, "", -1);
    $str4 .= "\"";
    
    $str5 = substr_replace($str5, "", -1);
    $str5 .= "\"";

    $str6 = substr_replace($str6, "", -1);
    $str6 .= "\"";

    $json  = $str;
    $json .= $str0 . $str1 . ", ";
    $json .= $str0 . $str2 . ", ";
    $json .= $str0 . $str3 . ", ";
    $json .= $str0 . $str4 . ", ";
    $json .= $str0 . $str5 . ", ";
    $json .= $str0 . $str6 . "]}; ";
    
    mysql_close();
    return $json;
  }
 
  function logout()
      {

        unset($_SESSION['userid']);

        session_destroy();
        $rsp = 'rsp = {"function":"logout"}';
        output($rsp);

      }
   
  function chart_multi($locs)
  {
    if (empty($locs) || $locs[0] == "national")
      $locs[] = "albany, ny";
    //echo $locs[0];
				mysql_connect("localhost", "websys", "websys");
				mysql_select_db("final_proj");
    $str = "rsp = {\"function\":\"charts\",\"chart_src\":[";
    $str0 ="\"http://chart.apis.google.com/chart?chs=600x400&amp;chco=00FF00&amp;chts=000000,20&amp;chf=bg,s,EFEFEF&amp;chbh=a&amp;cht=bvg&amp;";
    $str1="chtt=Average+Price+(Dollars)&amp;chd=t:";
    $str2="chtt=Average+Gender+Ratio+(Females+to+Males)&amp;chd=t:";
    $str3="chtt=Average+Income+(Dollars)&amp;chd=t:";
    $str4="chtt=Average+Age+(Years)&amp;chd=t:";
    $str5="chtt=Average+Population+(People)&amp;chd=t:";
    $str6="chtt=Average+Total+Listings+(Listings)&amp;chd=t:";

    $max_avg_p=0;
    $max_avg_gr = 0;
    $max_avg_inc = 0;
    $max_avg_age = 0;
    $max_pop = 0;
    $max_tot_list = 0;
    
    $labels = array();

    foreach($locs as $item)
    {
      //echo $item . "<br/>";
      $regarr = explode(",", $item);

      if(sizeof($regarr)==2)
      {
       $place  = $regarr[0];
       $state  = trim($regarr[1]);
       $labels[] = $place . ", " . $state;

      }
      else
      {
        $place="";
        $state = $regarr[0];
        $labels[] = $state;
      }
      //only state
      if($place=="")
      {
        $sql = "SELECT avg(avg_price) AS AvgPrice, avg(gender_ratio) AS AvgGenderRatio,
                       avg(avg_income) AS AvgIncome, avg(avg_age) AS AvgAge,
                       avg(population) AS AvgPopulation, avg(total_listings) AS AvgTotalListings
                  FROM stats
                  JOIN locations ON stats.location_id = locations.id
                  WHERE locations.state = '" . $state . "'
                  GROUP BY locations.state";
        if (($data = mysql_query($sql)) == null)
          output(mysql_error()."<p>$sql</p>");
        $stats="<b>" . $state . "</b>";
        //echo $sql;

        if($row = mysql_fetch_array($data))
        {
            $avg_p = $row['AvgPrice'];
            $avg_gr = $row['AvgGenderRatio'];
            $avg_inc = $row['AvgIncome'];
            $avg_age = $row['AvgAge'];
            $pop = $row['AvgPopulation'];
            $tot_list = $row['AvgTotalListings'];
           
            if($avg_p > $max_avg_p) $max_avg_p = $avg_p;
            if($avg_gr > $max_avg_gr) $max_avg_gr = $avg_gr;
            if($avg_inc > $max_avg_inc) $max_avg_inc = $avg_inc;
            if($avg_age > $max_avg_age) $max_avg_age = $avg_age;
            if($pop > $max_pop) $max_pop = $pop;
            if($tot_list > $max_tot_list) $max_tot_list = $tot_list;
           
            $str1 .= $avg_p . ",";
            $str2 .= $avg_gr . ",";
            $str3 .= $avg_inc . ",";
            $str4 .= $avg_age . ",";
            $str5 .= $pop . ",";
            $str6 .= $tot_list . ",";
        }
      }
      else //city and state
      {
        //get city id
        $sql = "SELECT id FROM locations WHERE name = '" . $place . "' AND state = '" . $state . "'";
        //echo $sql;

        if(!($loc = mysql_query($sql)))
          badreq(mysql_error()." ".$sql);


        if($row = mysql_fetch_array($loc))
        {
          $city_id = $row['id'];
          $sql2 = "SELECT * FROM stats where location_id = " . $city_id . " GROUP BY location_id";

          if(!($data = mysql_query($sql2)))
            badreq(mysql_error()." ".$sql2);


          $stats = "<b>" . $place . ", " . $state . "</b><br/>";
          while($row2 = mysql_fetch_array($data))
          {
            $avg_p = $row2['avg_price'];
            $avg_gr = $row2['gender_ratio'];
            $avg_inc = $row2['avg_income'];
            $avg_age = $row2['avg_age'];
            $pop = $row2['population'];
            $tot_list = $row2['total_listings'];

            if($avg_p > $max_avg_p) $max_avg_p = $avg_p;
            if($avg_gr > $max_avg_gr) $max_avg_gr = $avg_gr;
            if($avg_inc > $max_avg_inc) $max_avg_inc = $avg_inc;
            if($avg_age > $max_avg_age) $max_avg_age = $avg_age;
            if($pop > $max_pop) $max_pop = $pop;
            if($tot_list > $max_tot_list) $max_tot_list = $tot_list;

            $str1 .= $avg_p . ",";
            $str2 .= $avg_gr . ",";
            $str3 .= $avg_inc . ",";
            $str4 .= $avg_age . ",";
            $str5 .= $pop . ",";
            $str6 .= $tot_list . ",";

          }
        }
      }

    }
    $max = "Max Data<br/>";
    $max .= "avg_p: " . number_format($max_avg_p, 2) . "<br/>";
    $max .= "avg_gr: " . number_format($max_avg_gr, 2) . "<br/>";
    $max .= "avg_inc: " . number_format($max_avg_inc, 2) . "<br/>";
    $max .= "avg_age: " . number_format($max_avg_age, 0) . "<br/>";
    $max .= "max_pop: " . number_format($max_pop, 0) . "<br/>";
    $max .= "max_tot_list :" . number_format($max_tot_list, 0) . "<br/>";
    
    $str1 = substr_replace($str1, "", -1);
    $str1 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_p . "," . $max_avg_p/10 . "&amp;chds=0," . $max_avg_p . "&amp;chl=";

    $str2 = substr_replace($str2, "", -1);
    $str2 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_gr . "," . $max_avg_gr/10 . "&amp;chds=0," . $max_avg_gr . "&amp;chl=";

    $str3 = substr_replace($str3, "", -1);
    $str3 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_inc . "," . $max_avg_inc/10 . "&amp;chds=0," . $max_avg_inc . "&amp;chl=";

    $str4 = substr_replace($str4, "", -1);
    $str4 .= "&amp;chxt=y&amp;chxr=0,0," . $max_avg_age . "," . $max_avg_age/10 . "&amp;chds=0," . $max_avg_age . "&amp;chl=";

    $str5 = substr_replace($str5, "", -1);
    $str5 .= "&amp;chxt=y&amp;chxr=0,0," . $max_pop . "," . $max_pop/10 . "&amp;chds=0," . $max_pop . "&amp;chl=";

    $str6 = substr_replace($str6, "", -1);
    $str6 .= "&amp;chxt=y&amp;chxr=0,0," . $max_tot_list . "," . $max_tot_list/10 . "&amp;chds=0," . $max_tot_list . "&amp;chl=";

    
    foreach($labels as $label)
    {
      $str1 .= $label . "|";
      $str2 .= $label . "|";
      $str3 .= $label . "|";
      $str4 .= $label . "|";
      $str5 .= $label . "|";
      $str6 .= $label . "|";

    }
    $str1 = substr_replace($str1, "", -1);
    $str1 .= "\"";

    $str2 = substr_replace($str2, "", -1);
    $str2 .= "\"";
    
    $str3 = substr_replace($str3, "", -1);
    $str3 .= "\"";
    
    $str4 = substr_replace($str4, "", -1);
    $str4 .= "\"";
    
    $str5 = substr_replace($str5, "", -1);
    $str5 .= "\"";

    $str6 = substr_replace($str6, "", -1);
    $str6 .= "\"";

    $json = $str;
    $json .= $str0 . $str1 . ", ";
    $json .= $str0 . $str2 . ", ";
    $json .= $str0 . $str3 . ", ";
    $json .= $str0 . $str4 . ", ";
    $json .= $str0 . $str5 . ", ";
    $json .= $str0 . $str6 . "]}; ";
    
    mysql_close();
    output($json);
  }

function output( $text) {
	echo 'function show_me_the_money(){ ';
	echo $text;
	echo ' }';
 die();	
}
  /* 
		   begin execution area
		*/ 

mysql_connect("localhost", "websys", "websys");
mysql_select_db("final_proj");

if (empty($_GET) && empty($_POST)) badreq("blank req");
 
if (!empty($_GET))
{
	$fnc = $_GET['function'];
	
	if (!($fnc == "NOP") && !($fnc == "add_user")){
		$ssid = $_GET['ssid'];
		if (!checkSession($ssid) && (!($fnc == "add_user"))) badreq("must be logged in");
	}
	   
	if (empty($fnc)) badreq("no function supplied"); 
				 
	$fnc = urldecode($fnc);
	$fnc = strtolower($fnc);

	switch ($fnc) 
	{
		case "chart_multi":
			$arr = getChartArr();
			output(chart_multi($arr));
			break;
		case "chart_base":
			chart_base(); // four????????????????????
			break;
		case "delete_listing":
			delete_listing();
			break;
		case "user_settings":
			user_settings();
			break;
		case "settings_remove":
			settings_remove();
			break;
		case "settings_add":
			settings_add();
			break;
		case "home":
			home();
			break;
		case "table":
			fnc_table();
			break;
		case "delete_user":
			delUser();
			break;
		case "logout":
			logout();
			break;
		case "add_user":
			addUser();
			break;
		case "age_gender":
			get_age_gender();
			break;
		default:
			badreq("no such function");
	}
}

if (!empty($_POST)) 
{
auth_user(); 
}  
/* 
	   end execution area
	*/
?>
